package com.zat.mes.andrmes.dofun.todo

import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.dofun.main.vm.TodoModel
import com.zat.mes.andrmes.dofun.todo.adapter.TodoAdapter
import com.zat.mes.andrmes.event.TodoEventMessage
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.PreferencesUtil
import kotlinx.android.synthetic.main.activity_todo_new.*
import kotlinx.android.synthetic.main.layout_title.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 新的待办事项 activity
 */
class TodoNewActivity : BaseActivity() {

    private var todoModel: TodoModel? = null
    private var empId: Long = 0
    override fun init() {
        initView()
        initData()
    }

    /**
     * 初始化数据
     */
    private fun initData() {
        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        empId = loginResultBean.empid
        val empName = loginResultBean.empname
        recyclerTodoAc.layoutManager = LinearLayoutManager(this)
        val todoAdapter = TodoAdapter(R.layout.item_todo_fragment, empId, empName)
        recyclerTodoAc.adapter = todoAdapter
        todoModel = ViewModelProvider(this).get(TodoModel::class.java)

        todoModel?.getTodoList()?.observe(this, Observer {
            closeLoading()
            todoAdapter.setNewData(ArrayList())
            if (it != null && it.result != null) {
                if (it.result.size <= 0) {
                    setEmptyVisible()
                } else {
                    setEmptyGone()
                }
                todoAdapter.addData(it.result)
            } else {
                setEmptyVisible()
            }

        })
        todoModel?.loadTodoList(1, 2, empId, "0")
        showLoading()
    }

    /**
     * 初始化view
     */
    private fun initView() {
        setContentView(R.layout.activity_todo_new)
        tVtitle.text = getString(R.string.title_todo)
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTodoEvent(event: TodoEventMessage) {
        //todolist
        Log.e("eventbus", "todo")
        android.os.Handler()
            .postDelayed(Runnable { todoModel?.loadTodoList(1, 2, empId, "0") }, 500)

    }
}
